from flask import url_for
from flask_restful import Resource

from model.crud import UpdateInstance, QueryOneInstance, DeleteInstance
from model.tables import Like
from restful.data import DataPid
from restful.response import ResponseConflict, ResponseSuccess
from restful.session import current_user_required,data


class LikeOrCancel(Resource):
    @current_user_required
    @data(DataPid())
    def get(self,data,current_user):
        like = QueryOneInstance(Like,{'pid':data['pid'],'uid':current_user.id})

        return ResponseSuccess(data={
            'liked': bool(like),
        })

    @current_user_required
    @data(DataPid())
    def post(self,data,current_user):
        like = QueryOneInstance(Like,{'pid':data['pid'],'uid':current_user.id})

        if like:
            return ResponseConflict("勿重复点赞")

        UpdateInstance(Like(uid=current_user.id,pid=data['pid']))
        return ResponseSuccess("已点赞")

    @current_user_required
    @data(DataPid())
    def delete(self,data,current_user):
        like = QueryOneInstance(Like,{'uid':current_user.id,'pid':data['pid']})

        if not like:
            return ResponseConflict("点赞不存在")

        DeleteInstance(like)
        return ResponseSuccess("已取消点赞")
